package productConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock版本的同步控制
 */
public class demo4 {
    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程A").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程C").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程D").start();
    }
}

class Data2{
    private int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increase() throws InterruptedException {

        try {
            lock.lock();
            while(num != 0){
                condition.await();
            }
            num++;
            System.out.println("当前线程："+Thread.currentThread().getName()+" num:"+num);
            condition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrease() throws InterruptedException {
        try {
            lock.lock();
            while(num == 0){
                condition.await();
            }
            num--;
            System.out.println("当前线程："+Thread.currentThread().getName()+" num:"+num);
            condition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}